import sys
import os


#抽象观察对象类
class Observable:
    def __init__(self):
        self.observers = []

    def attach(self, observer):
        print(type(observer), 'has been attached!')
        self.observers.append(observer)

    def detach(self, observer):
        print(type(observer), 'has been detached!')
        self.observers.remove(observer)

    def notify(self):
        for o in self.observers:
            o.update()


#具象观察对象类
class ConcreteObservable(Observable):
    def __init__(self):
        Observable.__init__(self)
        self.state = None

    def set_state(self, state):
        self.state = state
        self.notify()

    def get_state(self):
        return self.state


#具象观察者类
class ConcreteObserver:
    def __init__(self, observable):
        self.observable = observable

    def update(self):
        print(type(self), self.observable.get_state())


if __name__ == '__main__':
    observable = ConcreteObservable()
    # 构建观察者
    observer = ConcreteObserver(observable)
    # 观察者注册
    observable.attach(observer)
    # 改变观察对象状态，产生输出
    observable.set_state('State Changed1!')
    # 观察者被取消登录
    observable.detach(observer)
    # 再次改变观察对象状态，不产生输出
    observable.set_state('State Changed2!')


